package org.vy.dal.common;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class DOCache {

	private static final Map<String, Map<String, Method>> readcache = new HashMap<String, Map<String, Method>>();
	
	private static final Map<String, Map<String, Method>> writecache = new HashMap<String, Map<String, Method>>();
	
	public static Map<String, Method> getReadMap(Class<?> clz){
		try{
			if(!readcache.containsKey(clz.getSimpleName())){
				fillMap(clz);
			}
			return readcache.get(clz.getSimpleName());
		}catch(Exception e){
			e.printStackTrace();
		}
		return new HashMap<String, Method>();
	}
	
	public static Map<String, Method> getWriteMap(Class<?> clz){
		try{
			if(!writecache.containsKey(clz.getSimpleName())){
				fillMap(clz);
			}
			return writecache.get(clz.getSimpleName());
		}catch(Exception e){
			e.printStackTrace();
		}
		return new HashMap<String, Method>();
	}
	
	private static void fillMap(Class<?> clz) throws Exception{
		Map<String, Method> readMap = new HashMap<String, Method>();
		Map<String, Method> writeMap = new HashMap<String, Method>();
		BeanInfo beanInfo = Introspector.getBeanInfo(clz);
		PropertyDescriptor[] pdList = beanInfo.getPropertyDescriptors();
		Field[] fields = clz.getDeclaredFields();
		
		for(Field fld : fields){
			for(PropertyDescriptor pd : pdList){
				if(fld.getName().equalsIgnoreCase("m_"+pd.getName())){
					DBField anno = fld.getAnnotation(DBField.class);
					readMap.put(fld.getName(), pd.getReadMethod());
					writeMap.put(anno.value().toUpperCase(), pd.getWriteMethod());
				}
			}
		}
		readcache.put(clz.getSimpleName(), readMap);
		writecache.put(clz.getSimpleName(), writeMap);
	}
}
